<?php
/**
 * @file
 */
/**
 * Menu callback: Generates a listing of promoted entities.
 */
function customer_page_default($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;
  switch ($op) {
    case t('Add new customer'):
    case 'create':
      module_load_include('inc', 'customer', 'customer.form');
      $build['customer_form'] = drupal_get_form('customer_form');
      break;
    default:
      if (!empty($_POST['agencies']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $build['customer_multiple_delete_confirm'] = drupal_get_form('customer_multiple_delete_confirm');
      }
      else {
        $build['customer_filter_form'] = drupal_get_form('customer_filter_form');
        $build['customer_page_agencies'] = drupal_get_form('customer_page_agencies');
      }
  }
  return $build;
}

/**
 * Form builder; User administration page.
 *
 * @ingroup forms
 * @see customer_admin_customer_validate()
 * @see customer_admin_customer_submit()
 */
function customer_page_agencies() {
  $header = array(
    'name' => array('data' => t('Name'), 'field' => 'a.name'),
    'address' => array('data' => t('Address')),
    'tel' => array('data' => t('Telephone'), 'field' => 'a.tel'),
    'fax' => array('data' => t('Fax')),
    'hangding_fee' => array('data' => t('Hangding Fee'), 'field' => 'a.hangding_fee'),
    'remark' => array('data' => t('Remark'), 'field' => 'a.remark'),
    'status' => array('data' => t('Status'), 'field' => 'a.status'),
    'uid' => array('data' => t('User'), 'field' => 'a.uid'),
    'modified' => array('data' => t('Modified'), 'field' => 'a.modified'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('customer', 'a');
  $query->leftJoin('users', 'u', "a.uid = u.uid");
  customer_build_filter_query($query);

  $count_query = clone $query;
  $count_query->addExpression('COUNT(a.aid)');

  $query->addField('u', 'name', 'username');
  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('a', array('aid', 'name', 'tel', 'fax', 'hangding_fee', 'remark', 'status', 'uid', 'modified'))
    ->limit(50)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
  );
  $options = array();
  foreach (module_invoke_all('customer_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'unblock',
  );
  $options = array();
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  foreach ($result as $customer) {
    $entity = customer_load($customer->aid);
    $address = field_view_value('customer', $entity, 'customer_address', $entity->customer_address[LANGUAGE_NONE][0]);
    $options[$customer->aid] = array(
      'name' => $customer->name,
      'address' => array('data' => $address),
      'tel' => $customer->tel,
      'fax' => $customer->fax,
      'hangding_fee' => $customer->hangding_fee,
      'remark' => $customer->remark,
      'status' =>  $customer->status,
      'uid' => $customer->name,
      'modified' => date('d-m-Y H:i', $customer->modified),
      'operations' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => t('edit'),
          '#href' => "ffs/customer/edit/{$customer->aid}",
          '#options' => array('query' => $destination)
        )
      ),
    );
  }

  $form['agencies'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No customer available.'),
  );
  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Submit the user administration update form.
 */
function customer_agencies_submit($form, &$form_state) {
  $operations = module_invoke_all('customer_operations', $form, $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['agencies']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    }
    else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function customer_agencies_validate($form, &$form_state) {
  $form_state['values']['agencies'] = array_filter($form_state['values']['agencies']);
  if (count($form_state['values']['agencies']) == 0) {
    form_set_error('', t('No customer selected.'));
  }
}

/**
 * Extends a query object for customer administration filters based on session.
 *
 * @param $query
 *   Query object that should be filtered.
 */
function customer_build_filter_query(SelectQuery $query) {
  // Extend Query with filter conditions.
  $values = isset($_SESSION['customer_filter']) ? $_SESSION['customer_filter'] : array();
  foreach (module_invoke_all('customer_filters') as $key => $filter) {
    if (!empty($values[$key])) {
      if (isset($filter['base table'])) {
        list ($type, $table, $alias, $condition) = $filter['base table'];
        $query->addJoin($type, $table, $alias, $condition);
      }
      if (!empty($filter['field'])) {
        $operator = isset($filter['field']['operator']) ? $filter['field']['operator'] : "=";
        if (isset($filter['field']['value callback'])) {
          $values[$key] = call_user_func($filter['field']['value callback'], $values[$key]);
        }
        if (!empty($values[$key])) {
          $query->condition($filter['field']['field'], $values[$key], $operator);
        }
      }
    }
  }
}

/**
 * Form builder; Return form for user administration filters.
 *
 * @ingroup forms
 * @see customer_filter_form_submit()
 */
function customer_filter_form() {
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only agencies where'),
    '#theme' => 'exposed_filters__customer',
    '#tree' => TRUE
  );

  $session = isset($_SESSION['customer_filter']) ? $_SESSION['customer_filter'] : array();

  foreach (module_invoke_all('customer_filters') as $key => $filter) {
    if (!empty($filter['filter callback'])) {
      if (function_exists($filter['filter callback'])) {
        $form['filters'][$key] = call_user_func($filter['filter callback'], $session);
        continue;
      }
    }
    if (empty($filter['form element'])) {
      continue;
    }
    if (is_array($filter['form element'])) {
      $form['filters'][$key] = $filter['form element'];
    }
    else if (function_exists($filter['form element'])) {
      $form['filters'][$key] = call_user_func($filter['form element']);
    }
    if (!empty($form['filters'][$key]) && isset($session[$key])) {
      $form['filters'][$key]['#default_value'] = $session[$key];
    }
  }

  $form['filters']['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['filters']['actions']['filter'] = array(
    '#type' => 'submit',
    '#value' =>  t('Filter'),
  );
  if (count($session)) {
    $form['filters']['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Reset'),
    );
  }
  return $form;
}

/**
 * Process result from user administration filter form.
 */
function customer_filter_form_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  switch ($op) {
    case t('Filter'):
      // Apply every filter that has a choice selected other than 'any'.
      if (isset($form_state['values']['filters'])) {
        unset($form_state['values']['filters']['actions']);
        $_SESSION['customer_filter'] = $form_state['values']['filters'];
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['customer_filter']);
      break;
    case t('Reset'):
      $_SESSION['customer_filter'] = array();
      break;
    case t('Update'):
      return;
  }

  $form_state['redirect'] = customer_DEFAULT_MENU;
  return;
}

/**
 * Implements of hook_customer_filters()
 */
function customer_customer_filters() {
  $filters['name'] = array(
    'title' => 'Name',
    'form element' => array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => '',
      '#size' => 20
    ),
    'field' => array('field' => 'a.name', 'operator' => 'LIKE', 'value callback' => 'customer_db_like'),
  );
  $base_table = array('LEFT OUTER', 'field_data_customer_address', 'aa', 'aa.entity_id=a.aid');
  $filters['customer_address_thoroughfare'] = array(
    'title' => 'Address',
    'form element' => array(
      '#type' => 'textfield',
      '#title' => t('Address'),
      '#default_value' => '',
      '#size' => 20
    ),
    'base table' => $base_table,
    'field' => array('field' => 'aa.customer_address_thoroughfare', 'operator' => 'LIKE', 'value callback' => 'customer_db_like'),
  );
  $filters['customer_address_locality'] = array(
    'title' => 'City',
    'form element' => array(
      '#type' => 'textfield',
      '#title' => t('City'),
      '#default_value' => '',
      '#size' => 20
    ),
    'base table' => $base_table,
    'field' => array('field' => 'aa.customer_address_locality', 'operator' => 'LIKE', 'value callback' => 'customer_db_like'),
  );
  $filters['customer_address_country'] = array(
    'title' => 'Country',
    'form element' => array(
      '#type' => 'textfield',
      '#title' => t('Country'),
      '#default_value' => '',
      '#size' => 20
    ),
    'base table' => $base_table,
    'field' => array('field' => 'aa.customer_address_country', 'operator' => 'LIKE', 'value callback' => 'customer_db_like'),
  );
  return $filters;
}

function customer_db_like($string) {
  return !empty($string) ? "%%{$string}%%" : "";
}

function customer_multiple_delete_confirm($form, &$form_state) {
  $edit = $form_state['input'];

  $form['agencies'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  $agencies = customer_load_multiple(array_keys(array_filter($edit['agencies'])));
  foreach ($agencies as $aid => $customer) {
    $form['agencies'][$aid] = array(
      '#type' => 'hidden',
      '#value' => $aid,
      '#prefix' => '<li>',
      '#suffix' => check_plain($customer->name) . "</li>\n",
    );
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  return confirm_form($form,
    t('Are you sure you want to cancel these agencies?'),
    customer_DEFAULT_MENU, t('This action cannot be undone.'),
    t('Delete agencies'), t('Cancel'));
}

/**
 * Submit handler for mass-word delete form.
 */
function customer_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    customer_delete_multiple(array_keys($form_state['values']['agencies']));
    cache_clear_all();
    $count = count($form_state['values']['agencies']);
    watchdog('content', 'Deleted @count posts.', array('@count' => $count));
    drupal_set_message(format_plural($count, 'Deleted 1 post.', 'Deleted @count posts.'));
  }
  $form_state['redirect'] = customer_DEFAULT_MENU;
}

/**
 * Implements hook_customer_operations().
 */
function customer_customer_operations() {
  $operations = array(
    'countinue' => array(
      'label' => t('Publish selected content'),
      'callback' => 'customer_mass_update',
      'callback arguments' => array('updates' => array('status' => 0)),
    ),
    'unpublish' => array(
      'label' => t('Unpublish selected content'),
      'callback' => 'customer_mass_update',
      'callback arguments' => array('updates' => array('status' => 1)),
    ),
    'end' => array(
      'label' => t('Promote selected content to front page'),
      'callback' => 'customer_mass_update',
      'callback arguments' => array('updates' => array('status' => 2)),
    ),
    'delete' => array(
      'label' => t('Delete selected customer'),
      'callback' => NULL,
    ),
  );
  return $operations;
}

/**
 * Make mass update of entities, changing all nodes in the $entities array
 * to update them with the field values in $updates.
 */
function customer_mass_update($agencies, $updates) {
  // We use batch processing to prevent timeout when updating a large number
  // of nodes.
  if (count($agencies) > 10) {
    $batch = array(
      'operations' => array(
        array('_customer_mass_update_batch_process', array($agencies, $updates))
      ),
      'finished' => '_customer_mass_update_batch_finished',
      'title' => t('Processing'),
      // We use a single multi-pass operation, so the default
      // 'Remaining x of y operations' message will be confusing here.
      'progress_message' => '',
      'error_message' => t('The update has encountered an error.'),
      // The operations do not live in the .module file, so we need to
      // tell the batch engine which file to load before calling them.
      'file' => drupal_get_path('module', 'customer') . '/customer.page.inc',
    );
    batch_set($batch);
  }
  else {
    foreach ($agencies as $aid) {
      _customer_mass_update_helper($aid, $updates);
    }
    drupal_set_message(t('The update has been performed.'));
  }
}

/**
 * Updates individual entities when fewer than 10 are queued.
 */
function _customer_mass_update_helper($aid, $updates) {
  $customer = customer_load($aid, TRUE);
  // For efficiency manually save the original customer before applying any changes.
  $customer->original = $customer;
  foreach ($updates as $name => $value) {
    $customer->$name = $value;
  }
  customer_save($customer);
  return $customer;
}

/**
 * Executes a batch operation for customer_mass_update().
 *
 */
function _customer_mass_update_batch_process($agencies, $updates, &$context) {
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($agencies);
    $context['sandbox']['agencies'] = $agencies;
  }

  // Process nodes by groups of 5.
  $count = min(5, count($context['sandbox']['agencies']));
  for ($i = 1; $i <= $count; $i++) {
    // For each nid, load the node, reset the values, and save it.
    $aid = array_shift($context['sandbox']['agencies']);
    $customer = _customer_mass_update_helper($aid, $updates);

    // Store result for post-processing in the finished callback.
    $context['results'][] = l($customer->name, customer_DEFAULT_MENU . '/' . $customer->aid);

    // Update our progress information.
    $context['sandbox']['progress']++;
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Menu callback: Reports the status of batch operation for customer_mass_update().
 */
function _customer_mass_update_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('The update has been performed.'));
  }
  else {
    drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
    $message = format_plural(count($results), '1 item successfully processed:', '@count items successfully processed:');
    $message .= theme('item_list', array('items' => $results));
    drupal_set_message($message);
  }
}